package com.lk.config;

import com.lk.handler.CustomerAccessDeniedHandler;
import com.lk.handler.CustomerAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * 资源服务器
 *
 * @author : com.com.lk
 * @date 2021/11/23 14:05
 **/
@EnableResourceServer
@Configuration
public class ResourceAuthorized extends ResourceServerConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
//    @Autowired
//    private TokenStore tokenStore;

    @Autowired
    private SecurityIgnoreConfig securityIgnoreConfig;
    
    @Autowired
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;

    @Autowired
    private CustomerAuthenticationEntryPoint customerAuthenticationEntryPoint;

    @Bean
    public TokenStore jdbcTokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("product_api")//指定当前资源的id，非常重要！必须写！
                .tokenStore(jdbcTokenStore());//指定保存token的方式
        resources.accessDeniedHandler(customerAccessDeniedHandler)
                .authenticationEntryPoint(customerAuthenticationEntryPoint);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .antMatchers().access("#oauth2.hasScope('read')")
                .antMatchers(securityIgnoreConfig.getIgnore()).permitAll() // 白名单
                .anyRequest().authenticated()
                .and()
                .headers().addHeaderWriter((request, response) -> {
            response.addHeader("Access-Control-Allow-Origin", "*");//允许跨域
            if (request.getMethod().equals("OPTIONS")) {//如果是跨域的预检请求，则原封不动向下传达请求头信息
                response.setHeader("Access-Control-Allow-Methods", request.getHeader("Access-Control-Request-Method"));
                response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
            }
        });
        http.exceptionHandling()
                .accessDeniedHandler(customerAccessDeniedHandler) // 403
                .authenticationEntryPoint(customerAuthenticationEntryPoint);//401

        http.cors().disable().cors().disable();


    }


}
